// =====================客户端==========================

// 引入工具类
// 包含参数判空以及时间和随机数等函数的封装
const dateKit = require('./utils/dateKit');
// 包含数据库操作的函数封装
const dataKit = require('./utils/dataKit');
const clientService = require('./utils/clientService');
const util = require('./utils/util');



/**
 * 用户登录接口(已完成)
 * @param {} context  上下文
 * 接收前端拉取回来的用户数据
 * 通过该接口，将用户数据插入数据库
 * 向前端返回操作结果
 */
exports.login = async (context) => {
  // const NickName = 'tb78789798798';
  // const HeadImage = 'http://';
  // const openId = 'dwerwerewrewsdsf';
  const { NickName, HeadImage } = context.data;
  const { openId } = context;
  const CurrTime = await dateKit.getCurrentDateTime();

  // 检查前端传回来的昵称是否为空
  if (!NickName) {
    return { code: -1, msg: '用户昵称不能为空！' }
  }

  // 查询数据库，检测数据库内是否有该用户的信息
  let userInfo = await dataKit.findOne(context, 'c_user', {
    open_id: openId
  })

  // 如果数据库中没有该用户的信息，就封装一个对象，将用户信息封装起来
  if (!userInfo) {
    userInfo = {
      open_id: openId,
      nick_name: NickName,
      head_image: HeadImage,
      creat_time: CurrTime,
      //乐观锁
      version: 0
    }
  }

  // 登录时间
  userInfo.login_time = CurrTime

  //  数据库插入操作
  await dataKit.insertOrUpdate(context, 'c_user', userInfo);
  return { code: 0, msg: "登录成功！", data: openId };
};




/**
 * 填写收货地址
 */
exports.saveAddress = async (context) => {
  const { openId } = context;
  let { name, phone, province, city, area, address } = context.data;
  const current = await dateKit.getCurrentDateTime();
  let check = util.checkParamsNull(context, "name,phone,province,city,area,address");
  if (check) {
    return check;
  }

  let userInfo = await dataKit.findOne(context, "c_user", { open_id: openId });

  let deliveryExist = await dataKit.findOne(context, "delivery", { open_id: openId});

  delivery = {
    name,
    nick_name: userInfo.nick_name,
    open_id: openId,
    phone,
    province,
    city,
    area,
    address,
    create_time: current
  };

  if (deliveryExist) {
    delivery._id = deliveryExist._id;
  }
  let insertResult = await dataKit.insertOrUpdate(context, "delivery", delivery);
  if (!insertResult) return { code: -1, msg: '保存失败' }

  return { code: 1, msg: "保存成功", data: delivery };
}


/**
 * 修改收货地址
 */
exports.updateAddress = async (context) => {
  const { openId } = context;
  let { cdkey, phone, name, address } = context.data;
  let check = util.checkParamsNull(context, "phone,name,address");
  if (check) {
    return check;
  }

  let msgExist = await dataKit.findOne(context, "task_log", { 
    open_id: openId,
    cdkey:cdkey
    }
  );

  msg = {
    cdkey:cdkey,
    open_id:openId,
    address:address,
    phone:phone,
    name:name
  };

  if (msgExist) {
    msg._id = msgExist._id;
  }
  let insertResult = await dataKit.insertOrUpdate(context, "task_log", msg);
  if (!insertResult) return { code: -1, msg: '保存失败' }

  return { code: 1, msg: "修改成功", data: msg };
}


/**
 * 查看收货地址
 * @param {} context 
 */
exports.checkAddress = async (context) => {
  const { openId } = context;
  let delivery = await dataKit.findOne(context, "delivery", { open_id: openId});
  let data = delivery.province+delivery.area+delivery.area+delivery.address;
  return { code: 1, msg: "收货地址", data: data };
  
}


/**
 * 查看收货地址
 * @param {} context 
 */
exports.lookAddress = async (context) => {
  const { openId } = context;
  const { cdkey } = context.data;
  let delivery = await dataKit.findOne(context, "task_log", { open_id: openId, cdkey:cdkey});
  let data = delivery.address;
  return { code: 1, msg: "收货地址", data: data };
  
}


/**
 * 兑换接口
 * @param {*} context 
 */
exports.redeem = async (context) => {
  const { openId } = context;
  const { cdkey } = context.data;
  let redeem = await dataKit.findOne(context, "cdkey", { cdkey: cdkey});
  if(!redeem) return {code: -1,msg:"兑换码不存在"};
  if(redeem.state !=1){
    return {code: -2,msg:"该兑换码已被兑换过了"}
  }

  if(redeem.state == 1){
    await dataKit.update(context, 'cdkey', {
      cdkey: cdkey
    }, {
      state: 0
    })
  }
  
  var task = {
    cdkey: cdkey,
    open_id:openId,
    address: null,
    phone:null,
    name:null
  }
  await dataKit.insertOne(context, 'task_log', task);
  return {code: 1,msg:"兑换成功"}

}


/**
 * 查看奖品
 * @param {*} context 
 */
exports.checkPrize = async (context) => {
    const { openId } = context;
    const result = await context.cloud.db.collection('task_log').find(
    {
      open_id: openId
    }
  );
  return result;
}


/**
 * 插入数据
 */

exports.insertCDKEY = async (context) => {

  var str = ["1","2","3","4","5","1","2","3","4","5D5D5D5D5D","6","1","2","3","4","5","1","2","3","4","5","7","1","2","3","4","5","1","2","3","4","5"];
  a:for(var i =0;i<str.length;i++){
    const cdkeystr = str[i];
    var cdkey = {
      cdkey:cdkeystr,
      state:1
    }
    let redeem = await dataKit.findOne(context, "cdkey", { cdkey: cdkeystr});
    
    if(redeem != null){
      continue a;
    }
    await dataKit.insertOne(context, 'cdkey', cdkey);

  }
}



